package LeetCode1;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

//二叉树的中序遍历
public class Num94 {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        //递归方法
//        inorder(root,ret);
        //非递归方法
        if (root == null) {
            return ret;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        //当前走到的节点
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 此时cur为空，说明走到了null，此时栈顶就存放了左树为空
            cur = stack.pop();
            ret.add(cur.val);
            //访问右树
            cur = cur.right;
        }
        return ret;
    }

    private void inorder(TreeNode root, List<Integer> ret) {
        if (root == null) {
            return;
        }
        inorder(root.left, ret);
        ret.add(root.val);
        inorder(root.right, ret);
    }

}
